﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
///FileOperation 的摘要说明
/// </summary>
public class FileOperation
{
    public FileOperation()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }

    private static Encoding fileEncoding = Encoding.GetEncoding("GB2312");//文件操作编码

    #region 文件上传
    /// <summary>
    /// 普通上传
    /// </summary>
    /// <param name="page">Page page 当前页面</param>
    /// <param name="path">文件保存的路径</param>
    /// <param name="fileUp">上传控件对象</param>
    /// <returns>上传后的新文件路径</returns>
    public static string[] FileUpload(System.Web.UI.Page page, string path, System.Web.UI.WebControls.FileUpload fileUp)
    {
        if (fileUp.HasFile)
        {
            string[] imgType = new string[] { ".jpg", ".jpeg", ".gif", ".png", ".icon", ".bmp" };
            int contentSize = fileUp.PostedFile.ContentLength;      //文件大小
            if (contentSize > 2097152)
            {
                return new string[] { "false", "图片大于2M不能上传!" };
            }
            string fileName = fileUp.FileName;                      //文件名
            string fileExtension = Path.GetExtension(fileName);     //文件后缀
            int i = 0;
            foreach (string ty in imgType)
            {
                if (ty == fileExtension.ToLower())
                    i++;
            }
            if (i == 0)
                return new string[] { "false", "只能上传格式为{jpg|jpeg|gif|png|icon|bmp}的图片!" };
            //string contentType = fileUp.PostedFile.ContentType;     //文件的MIME内容类型

            //文件改名
            System.Threading.Thread.Sleep(1);

            string newsFileName = Guid.NewGuid() + fileExtension;   //新文件              

            if (path.LastIndexOf("/") == (path.Length - 1))
                path = path + string.Format("{0:yyyyMMdd}", DateTime.Now) + "/";
            else
                path = path + "/" + string.Format("{0:yyyyMMdd}", DateTime.Now) + "/";

            string fullpath = HttpContext.Current.Server.MapPath(path);
            if (!Directory.Exists(fullpath))
                Directory.CreateDirectory(fullpath);
            fileUp.SaveAs(fullpath + newsFileName);

            return new string[] { "true", path + newsFileName };
        }
        else
        {
            return new string[] { "false", "上传不能为空!" };
        }
    }
    #endregion

    #region 文件下载
    /// <summary>
    /// 下载文件
    /// </summary>
    /// <param name="fileName">文件路径</param>
    /// <param name="page">页面对象</param>
    public static void FileDown(string fileName, System.Web.UI.Page page)
    {
        if (!string.IsNullOrEmpty(fileName))
        {
            string filePath = page.Server.MapPath("~/" + fileName);//这里注意了,你得指明要下载文件的路径.

            if (System.IO.File.Exists(filePath))
            {
                FileInfo file = new FileInfo(filePath);
                page.Response.Clear();
                page.Response.ClearContent();
                page.Response.ClearHeaders();


                page.Response.AddHeader("Content-Disposition", "attachment; filename=" + page.Server.UrlEncode(file.Name)); //解决中文文件名乱码    
                page.Response.AddHeader("Content-length", file.Length.ToString());
                page.Response.AddHeader("Content-Transfer-Encoding", "binary");
                page.Response.ContentType = "appliction/octet-stream";
                page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); //解决中文乱码
                page.Response.WriteFile(file.FullName);
                page.Response.End();

            }
            else
            {
                page.ClientScript.RegisterStartupScript(page.GetType(), "", "alert('对不起,您预下载的文件已不存在！')", true);
            }
        }
    }
    #endregion

    #region 获取动态文件的源文件
    /// <summary>
    /// 获取动态文件的源文件
    /// </summary>   
    public static string getMakeHtmlStr(string aspxpathname)//(获取动态文件的源文件)
    {
        StringWriter swriter = new StringWriter();
        HttpContext.Current.Server.Execute(aspxpathname, swriter);
        string str = swriter.ToString();
        if (str.IndexOf("id=\"aspnetForm\"") > 0)
        {
            int a = str.IndexOf("<form");
            int b = str.IndexOf("<div>");
            if (b - a > 0)
            {
                string restr = str.Substring(a, b - a);
                str = str.Replace(restr, "");
                str = str.Replace("</form>", "");
            }
        }
        if (str.IndexOf("id=\"__VIEWSTATE\"") > 0)
        {
            int a = str.IndexOf("<div>");
            int b = str.IndexOf("</div>");
            if ((b - a + 6) > 0)
            {
                string restr = str.Substring(a, b - a + 6);
                str = str.Replace(restr, "");
            }

        }
        if (str.IndexOf("id=\"__EVENTVALIDATION") > 0)
        {
            int a = str.LastIndexOf("<div>");
            int b = str.LastIndexOf("</div>");
            if ((b - a + 6) > 0)
            {
                string restr = str.Substring(a, b - a + 6);
                str = str.Replace(restr, "");
            }
        }
        return str;
    }

    #endregion

    #region 根据路径读取文件内容
    /// <summary>
    /// 以文件流的形式读取静态文件模板
    /// </summary>
    /// <param name="path">文件相对路径</param>
    /// <returns>返回流字符串</returns>
    public static string ReaderFile(string path)
    {
        string content = "";
        //path = HttpContext.Current.Server.MapPath(path);
        if (File.Exists(path))
        {
            StreamReader StrReader = new StreamReader(path, fileEncoding, false);
            content = StrReader.ReadToEnd();
            StrReader.Close();
            StrReader.Dispose();
            return content;
        }
        else
        {
            throw new Exception("文件路径不存在!");
        }
    }
    #endregion

    #region 重新写入文件
    /// <summary>
    /// 重新写入文件
    /// </summary>
    /// <param name="fileStream">文件内容</param>
    /// <param name="FilePath">写入文件路径</param>  
    public static void StreamWriter(string fileStream, string FilePath)
    {
        StreamWriter StrWrite = new StreamWriter(FilePath, false, fileEncoding);
        StrWrite.Write(fileStream);
        StrWrite.Close();
        StrWrite.Dispose();
    }
    #endregion

    #region 修改文件
    /// <summary>
    /// 修改文件
    /// </summary>
    /// <param name="content">文件内容</param>
    /// <param name="FilePath">文件路径</param>
    public static void EditFile(string content, string filePath)
    {
        if (File.Exists(filePath))
        {
            StreamWriter StrWrite = new StreamWriter(filePath, false, fileEncoding);
            StrWrite.Write(content);
            StrWrite.Close();
            StrWrite.Dispose();
        }
        else
        {
            throw new Exception("预修改文件路径不存在!");
        }
    }
    #endregion

    #region 正则获取复合标签
    /// <summary>   
    /// 正则获取标签
    /// 0:标签
    /// 1:标签属性
    /// 2:内容
    /// </summary>
    /// <param name="fileStream">预分析的文件流</param>
    /// <param name="type">预分析的标签类型</param>
    /// <returns></returns>
    public static List<string[]> MatchGetTag(string fileStream, string type)
    {
        List<string[]> tags = new List<string[]>();
        string[] tag = new string[3];
        //(?is)(<tag:list[\w=\s\S]+?>)([\S\s]+?)</tag:list>
        //Regex regex = new Regex(@"(?is)(<tag:" + type + @"[\w=\s\""]+>)([\S\s]+?)</tag:" + type + ">");
        Regex regex = new Regex(@"(?is)(<tag:" + type + @".+?[""\s]+?>)(.+?)</tag:" + type + ">");

        Match match = regex.Match(fileStream);
        while (match.Success)
        {
            tag = new string[3];
            tag[0] = match.Groups[0].ToString();//标签
            tag[1] = match.Groups[1].ToString();//标签属性
            tag[2] = match.Groups[2].ToString();//内容
            tags.Add(tag);
            match = match.NextMatch();
        }
        return tags;
    }
    #endregion

    #region 正则获取复合标签属性
    /// <summary>
    /// 正则从属性集合获取属性值   
    /// 0:属性
    /// 1:值
    /// </summary>
    /// <param name="tag">预分析复合标签</param>
    /// <returns></returns>
    public static List<string[]> MatchGetTagAttr(string tag)
    {
        List<string[]> attrs = new List<string[]>();
        string[] attr = new string[2];
        //Regex regex = new Regex(@"\b(\w+)=\""([\w\d]+)\""");
        Regex regex = new Regex(@"\b(\w+)=\""(.+?)\""");
        Match match = regex.Match(tag);
        while (match.Success)
        {
            attr = new string[2];
            attr[0] = match.Groups[1].ToString();
            attr[1] = match.Groups[2].ToString();
            attrs.Add(attr);
            match = match.NextMatch();
        }
        return attrs;
    }
    #endregion

    #region 正则获取上一页|下一页
    /// <summary>
    /// 正则获取上一页|下一页
    /// 0:标签
    /// 1:特征
    /// 2:字符串长度
    /// </summary>
    /// <param name="fileStream">预分析的文件流</param>
    /// <returns></returns>
    public static List<string[]> MatchGetPaging(string fileStream)
    {
        List<string[]> attrs = new List<string[]>();
        string[] attr = new string[3];
        // 正则表达式对象
        Regex re = new Regex(@"(?is)<tag:(prev|next) len=""(\d+)""\s?/>");
        // Match 对象
        Match match = re.Match(fileStream);
        // 是否找到
        while (match.Success)
        {
            attr = new string[3];
            attr[0] = match.Groups[0].ToString();
            attr[1] = match.Groups[1].ToString();
            attr[2] = match.Groups[2].ToString();
            attrs.Add(attr);
            match = match.NextMatch();
        }
        return attrs;
    }
    #endregion
}
